﻿# -*- coding:utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings


AGENTLOG_CODE_CHOICES = (
    ('O', 'OK'),
    ('E', 'Error'),
    ('P', 'Ping'),
    ('M', 'Msg'),
)

class Plugin(models.Model):
    name = models.CharField(max_length=32,  verbose_name="Плагин")
    
    def __unicode__(self):
        return u"%s" % self.name   


class Agent(models.Model):
    apid = models.CharField(max_length=32)
    passkey = models.CharField(max_length=32)
    description = models.CharField(max_length=255, blank=True)
    enabled = models.BooleanField(blank=True, verbose_name="Включен")
    conn_interval = models.PositiveIntegerField()
    last_ip = models.IPAddressField(blank=True)
    last_conn_date = models.DateTimeField(blank=True, null=True, verbose_name="Дата последнего подключения") 

    class Meta:
        pass
    
    def __unicode__(self):
        return u"%s" % self.apid



#class TaskType(models.Model):
class Task(models.Model):
    plugin = models.ForeignKey(Plugin, verbose_name="Плагин") 
    code = models.CharField(max_length=32, verbose_name="Код")
    interval = models.PositiveIntegerField(verbose_name="Интервал повтора")    
    title = models.CharField(max_length=64, verbose_name="Название")
    description = models.TextField(blank=True, verbose_name="Описание")

    class Meta:
        ordering = ['code', 'title']

    def __unicode__(self):
        return u"%s" % (self.code)


'''
class TaskTypeParam(models.Model):
    task = models.ForeignKey(TaskType, verbose_name="тип задания")
    key = models.SlugField()
    value = models.CharField(max_length=255)
    
    def __unicode__(self):
        return u"%s" % self.key
'''


#class Task(models.Model):
class TaskQueue(models.Model):
    task = models.ForeignKey(Task, verbose_name="Задание") 
    start  = models.DateTimeField("Начало выполнения")    
    agent = models.ForeignKey(Agent, verbose_name="Агент")
    acknowledge = models.BooleanField(verbose_name="Задание получено")
    done = models.BooleanField(verbose_name="Задание выполнено")
    date = models.DateTimeField(auto_now_add=True, verbose_name="Дата") 
    user = models.ForeignKey(User, verbose_name="Пользователь")
    
    class Meta:
        ordering = ['start']
        
    def __unicode__(self):
        return u"%s - %s" % (self.task, self.start)       


'''
class TaskParam(models.Model):        
    task = models.ForeignKey(Task, verbose_name="Задание")
    key = models.SlugField()
    value = models.CharField(max_length=255)
    
    class Meta:
        pass
'''   
    
    
class AgentLog(models.Model):       
    agent = models.ForeignKey(Agent, verbose_name="Агент")
    task = models.ForeignKey(TaskQueue,  null=True, blank=True,  verbose_name="Задание")
    date = models.DateTimeField(auto_now_add=True, verbose_name="Дата")        
    message = models.CharField(max_length=255)  
    data = models.TextField(blank=True, verbose_name="Доп. данные")
    #agentdate = models.DateTimeField(blank=True, verbose_name="Дата агента")
    agentdate = models.CharField(max_length=32, blank=True, verbose_name="Дата агента")
    code = models.CharField(max_length=1, choices=AGENTLOG_CODE_CHOICES, verbose_name="Код")    
    
    class Meta:
        ordering = ['-date']
        

        
class TaskFieldManager(models.Manager):
    def get_query_set(self):
        return super(TaskFieldManager, self).get_query_set().order_by('ordering')



class TaskField(models.Model):
    """
    Definitions for custom fields that are glued onto each ticket.
    """
    task = models.ForeignKey(
        Task,
        verbose_name="тип задания"
        )
    
    name = models.SlugField(
        'Field Name',
        help_text='As used in the database and behind the scenes. Must be unique and consist of only lowercase letters with no punctuation.',
        unique=True,
        )

    label = models.CharField(
        'Label',
        max_length='30',
        help_text='The display label for this field',
        )

    help_text = models.TextField(
        'Help Text',
        help_text='Shown to the user when editing the ticket',
        blank=True,
        null=True
        )

    DATA_TYPE_CHOICES = (
            ('varchar', 'Character (single line)'),
            ('text', 'Text (multi-line)'),
            ('integer', 'Integer'),
            ('decimal', 'Decimal'),
            ('list', 'List'),
            ('boolean', 'Boolean (checkbox yes/no)'),
            ('date', 'Date'),
            ('time', 'Time'),
            ('datetime', 'Date & Time'),
            ('email', 'E-Mail Address'),
            ('url', 'URL'),
            ('ipaddress', 'IP Address'),
            ('slug', 'Slug'),
            ('file', 'File'),
            )

    data_type = models.CharField(
        'Data Type',
        max_length=100,
        help_text='Allows you to restrict the data entered into this field',
        choices=DATA_TYPE_CHOICES,
        )

    max_length = models.IntegerField(
        'Maximum Length (characters)',
        blank=True,
        null=True,
        )

    decimal_places = models.IntegerField(
        'Decimal Places',
        help_text='Only used for decimal fields',
        blank=True,
        null=True,
        )
        
    empty_selection_list = models.BooleanField(
        'Add empty first choice to List?',
        help_text='Only for List: adds an empty first entry to the choices list, which enforces that the user makes an active choice.',
        )        

    list_values = models.TextField(
        'List Values',
        help_text='For list fields only. Enter one option per line.',
        blank=True,
        null=True,
        )
    
    ordering = models.IntegerField(
        'Ordering',
        help_text='Lower numbers are displayed first; higher numbers are listed later',
        blank=True,
        null=True,
        )

    def _choices_as_array(self):
        from StringIO import StringIO
        valuebuffer = StringIO(self.list_values)
        choices = [[item.strip(), item.strip()] for item in valuebuffer.readlines()]
        valuebuffer.close()
        return choices
    choices_as_array = property(_choices_as_array)

    required = models.BooleanField(
        'Required?',
        help_text='Does the user have to enter a value for this field?',
        )

    staff_only = models.BooleanField(
        'Staff Only?',
        help_text='If this is ticked, then the public submission form will NOT show this field',
        )

    objects = TaskFieldManager()

    def __unicode__(self):
        return '%s' % (self.name)


class TaskFieldValue(models.Model):
    taskqueue = models.ForeignKey(
        TaskQueue,
        verbose_name='Task',
        )

    taskfield = models.ForeignKey(
        TaskField,
        verbose_name='Field',
        )

    value = models.TextField(blank=True, null=True)

    def __unicode__(self):
        return '%s / %s' % (self.taskqueue, self.taskfield)   

    class Meta:
        unique_together = ('taskqueue', 'taskfield'),   





     